#coding=utf-8
from pydemo.wiki.models import wiki
from django.template import loader, Context
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

def index(request, pagename=""):  
    """显示正常页面，对页面的文字做特殊的链接处理 """
    if pagename:
        #查找页面是否存在
        pages = wiki.objects.filter(pagename=pagename)
        if pages:
            #存在调用模板显示
            return process('wiki/page.html', pages[0])
        else:
            #不存在调用编辑模板
            return render_to_response('wiki/edit.html', {'pagename':pagename})
    else:
        page = wiki.objects.get(pagename="FrontPage")
        return process('wiki/page.html', page)
    
def edit(request, pagename):
    """显示编辑存在的页面"""   
    page = wiki.objects.get(pagename=pagename)
    return render_to_response('wiki/edit.html', {'pagename':pagename, 'content':page.content})

def save(request, pagename):
    """保存页面内容，老页面进行替换，新页面生成内容"""
    content = request.POST['content']
    pages = wiki.objects.filter(pagename=pagename)
    if pages:
        pages[0].content = content
        pages[0].save()
    else:
        page = wiki(pagename=pagename, content=content)
        page.save()
        
    return HttpResponseRedirect('/wiki/%s' % pagename)

import re

r = re.compile(r'\b(([A-Z]+[a-z]+){2,})\b')

def process(template, page):
    """处理页面链接，并将回车符转为<br>"""
    t = loader.get_template(template)
    content = r.sub(r'<a href="/wiki/\1">\1</a>', page.content)
    content = re.sub(r'[\n\r]+', '<br>', content)
    c = Context({'pagename':page.pagename, 'content':content})
    return HttpResponse(t.render(c))




   